//https://blog.csdn.net/LLL_liuhui/article/details/80361928
var _columns_action
var label_eva_wbal_test_unique_time="2002"
//var label_water_bala_companyId=1
//获取动态組列
$.ajax({
    url: "/entity_eva_ctest_sum/selectColumn",
    type: 'get',
    dataType: 'json',
    async: false,
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        _columns_action = data;
    }
});

//获取組中列数
function get_columns_num(fa_level) {
	var num;
	$.ajax({
	    type: "get",
	    url: "/meta_eva_ctest_sum/selectColumnNumByFaLevel",
	    dataType: 'json',
	    async: false,
	    contentType: "application/json; charset=utf-8",
	    data: {"faLevel": fa_level},
	    success: function (data) {
	        if (data['status'] == "success") {
	        	num = data['data'];
	        } else {
	            bootoast({
	                message: '删除失败\n' + data['msg'],
	                position: 'top',
	                type: 'danger',
	                timeout: 1.5,
	            });
	        }
	    }
	});
	return num;
}

var _columns =[
		[
			{checkbox: true, colspan: 1, rowspan: 3},
			{title: '用水分类', field: 'WATER_CLASS', align: 'center',	 valign: 'middle', colspan: 1, rowspan: 3},
			{title: '序号M', field: 'ID', align: 'center',	 valign: 'middle',	colspan: 1, rowspan: 3},
			{title: '序号', field: 'USE_ID', align: 'center',	 valign: 'middle',	colspan: 1, rowspan: 3},
			{title: '用水单元名称',field: 'WATER_UNIT_NAME', align: 'center', valign: 'middle', colspan: 1, rowspan: 3},
			{title: '新水量/(m³/h)', field: '', align: 'center',	 valign: 'middle', colspan: 2, rowspan: 1},
			{title: '重复利用水量', field: '', align: 'center',	 valign: 'middle',	colspan: 1, rowspan: 1},
			{title: '其他水量', field: '', align: 'center',	 valign: 'middle',	colspan: 1, rowspan: 1}
		],
		[
			{title: '常规水资源取水量',	field: '',	align: 'center',	valign: 'middle',	colspan: 1,	rowspan: 1},
			{title: '非常规水资源取水量',	field: '',	align: 'center',	valign: 'middle',	colspan: 1,	rowspan: 1}
		],
		[
			
		],
	]

//組裝動態列
$(function () {
	var num1 = get_columns_num(1);
	//修改常规水资源量長度
	_columns[1][0]['colspan'] = num1;
	//添加子項
	for(var i = 0; i < num1 ; i++) {
		var _column = [];
		_column['title'] = _columns_action[i].title;
		_column['field'] = _columns_action[i].field;
		_column['align'] = "center";
		_column['valign'] = "middle";
		_column['colspan'] = 1;
		_column['rowspan'] = 1;
		_columns[2].push(_column);
	}
	
	var num2 = get_columns_num(2);
	//修改非常规水资源量長度
	_columns[1][1]['colspan'] = num2;
	//添加子項
	for(var i = num1; i < num2+num1 ; i++) {
		var _column = [];
		_column['title'] = _columns_action[i].title;
		_column['field'] = _columns_action[i].field;
		_column['align'] = "center";
		_column['valign'] = "middle";
		_column['colspan'] = 1;
		_column['rowspan'] = 1;
		_columns[2].push(_column);
	}
	_columns[0][5]['colspan'] = num2+num1;
	
	var num3 = get_columns_num(3);
	//修改重复利用水量長度
	_columns[0][6]['colspan'] = num3;
	//添加子項
	for(var i = num2+num1; i < num3+num2+num1 ; i++) {
		var _column = [];
		_column['title'] = _columns_action[i].title;
		_column['field'] = _columns_action[i].field;
		_column['align'] = "center";
		_column['valign'] = "middle";
		_column['colspan'] = 1;
		_column['rowspan'] = 2;
		_columns[1].push(_column);
	}
	var num4 = get_columns_num(4);
	//修改其他水量量長度
	_columns[0][7]['colspan'] = num4;
	//添加子項
	for(var i = num3+num2+num1; i < num4+num3+num2+num1 ; i++) {
		var _column = [];
		_column['title'] = _columns_action[i].title;
		_column['field'] = _columns_action[i].field;
		_column['align'] = "center";
		_column['valign'] = "middle";
		_column['colspan'] = 1;
		_column['rowspan'] = 2;
		_columns[1].push(_column);
	}
	
	//修改表头，删除为0项
	//update_table_head();
});

var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#data_table').bootstrapTable({
            url: '/entity_eva_ctest_sum/select',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: false,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: false,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
            columns: _columns,
            onLoadSuccess: function(data){
            	//alert(JSON.stringify(data))
            	add_table_foot()//添加表尾
            	update_table_foot();//修改表尾
            	sumWater();//计算总计
            	mergeCells(data['rows'], 'WATER_CLASS', 1, '#data_table') //合并行
            },
            //导出
            showExport: true,                     //是否显示导出按钮
            exportTypes:['csv', 'doc', 'excel'], //['csv', 'txt', 'sql', 'doc', 'excel', 'xlsx', 'pdf'],           //导出文件类型
            exportDataType: "basic",             //basic当前页', 'all所有, 'selected'.
            exportOptions: {
                fileName: '企业水平衡测试统计表'+label_eva_wbal_test_unique_time,  //文件名称设置
                excelstyles: ['background-color', 'color', 'font-size', 'font-weight']
            },
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            label_id: label_water_bala_companyId,
        };
        //console.log(label_water_bala_companyId);
        return temp;
    };
    return oTableInit;
};


var ButtonInit = function () {
    var oInit = new Object();

    oInit.Init = function () {
        //初始化页面上面的按钮事件
        //新增按钮
        $("#btn_add").click(function () {
        	// 跳过 checkbox 和 id
        	$('#new_data_body').empty();
        	$('#new_data_body').append(create_column(_columns[0][1].title, 'new' + _columns[0][1].field, '',0));//水源類別
        	$('#new_data_body').append(create_column(_columns[0][3].title, 'new' + _columns[0][3].field, '',0));//
        	$('#new_data_body').append(create_column(_columns[0][4].title, 'new' + _columns[0][4].field, '',0));//
        	for (var i = 0; i < _columns_action.length; i++)
                $('#new_data_body').append(create_column(_columns_action[i].title, 'new' + _columns_action[i].field, '',0));
        	$("#newWATER_CLASS").append('<option value="主要生产用水">主要生产用水</option>');
        	$("#newWATER_CLASS").append('<option value="辅助生产用水">辅助生产用水</option>');
        	$("#newWATER_CLASS").append('<option value="附属生产用水">附属生产用水</option>');
            $('#new_data').modal()
        });
        
        //编辑按钮
        $("#btn_edit").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');
            if (arrselections.length > 1) {
                bootoast({
                    message: '只能选择一行进行编辑',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            $('#edit_data_body').empty();
            $('#edit_data_body').append(create_column(_columns[0][1].title, 'edit' + _columns[0][1].field, arrselections[0][_columns[0][1].field],1));//水源類別
        	$('#edit_data_body').append(create_column(_columns[0][3].title, 'edit' + _columns[0][3].field, arrselections[0][_columns[0][3].field],1));//
        	$('#edit_data_body').append(create_column(_columns[0][4].title, 'edit' + _columns[0][4].field, arrselections[0][_columns[0][4].field],1));//
        	for (var i = 0; i < _columns_action.length; i++)
                $('#edit_data_body').append(create_column(_columns_action[i].title, 'edit' + _columns_action[i].field, arrselections[0][_columns_action[i].field],1));
        	$("#editWATER_CLASS").append('<option value="主要生产用水">主要生产用水</option>');
        	$("#editWATER_CLASS").append('<option value="辅助生产用水">辅助生产用水</option>');
        	$("#editWATER_CLASS").append('<option value="附属生产用水">附属生产用水</option>');
        	$('#editWATER_CLASS').val(arrselections[0][_columns[0][1].field])
        	$('#edit_data').modal()
        });

        // 删除按钮
        $("#btn_delete").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }

            values=[];
            for(var i=0;i<arrselections.length;i++)
                values.push(arrselections[i].ID);
            
            bootbox.confirm({
                message: "确认要删除选择的数据吗？",
                locale: 'zh_CN',
                title: '操作提示',
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            type: "post",
                            url: "/entity_eva_ctest_sum/delete",
                            data: JSON.stringify(values),
                            contentType: "application/json",
                            success: function (data) {
                                if (data['status'] == "success") {
                                    bootoast({
                                        message: '删除成功',
                                        position: 'top',
                                        type: 'success',
                                        timeout: 1.5,
                                    });
                                    $("#data_table").bootstrapTable('refresh');
                                } else {
                                    bootoast({
                                        message: '删除失败\n' + data['msg'],
                                        position: 'top',
                                        type: 'danger',
                                        timeout: 1.5,
                                    });
                                }
                            }
                        });
                    }
                }
            })

        });


        //新增框内的提交 
        $('#new_data_submit').on('click', function () {
        	var values = []
        	values.push($('#new' + _columns[0][1].field).val());//水源類別
        	values.push($('#new' + _columns[0][3].field).val());
        	values.push($('#new' + _columns[0][4].field).val());
        	for (var i = 0; i < _columns_action.length; i++)
        		values.push($('#new' + _columns_action[i].field).val());
        	values.push(label_water_bala_companyId);//组号
        	
        	//alert(JSON.stringify(values));
            var message = valid($('#new' + _columns[0][3].field).val(),$('#new' + _columns[0][4].field).val());
            //console.log(values)
            if(message == null){
            	$.ajax({
                	type: "post",
                    url: "/entity_eva_ctest_sum/insert",
                    data: JSON.stringify(values),
                    contentType: "application/json",
                    success: function (data) {
                        if (data['status'] == "success") {
                            bootoast({
                                message: '插入成功',
                                position: 'top',
                                type: 'success',
                                timeout: 2,
                            });
                            $("#new_data").modal('hide');
                            $("#data_table").bootstrapTable('refresh');
                        } else {
                            bootoast({
                                message: '插入失败\n' + data['msg'],
                                position: 'top',
                                type: 'danger',
                                timeout: 2,
                            });
                        }
                    },
                    error: function () {
                        bootoast({
                            message: '通讯异常',
                            position: 'top',
                            type: 'danger',
                            timeout: 1.5,
                        });
                    }
                });
            }
            else{
            	bootoast({
                    message: message,
                    position: 'top',
                    type: 'danger',
                    timeout: 1.5,
                });
            }
            
        })

    };
    
  //编辑框内的提交
    $('#edit_data_submit').click(function () {
        var values = []
        var id = $("#data_table").bootstrapTable('getSelections')[0]['ID'];        
        values.push(id);
        values.push($('#edit' + _columns[0][1].field).val());//水源類別
    	values.push($('#edit' + _columns[0][3].field).val());
    	values.push($('#edit' + _columns[0][4].field).val());
    	for (var i = 0; i < _columns_action.length; i++)
    		values.push($('#edit' + _columns_action[i].field).val());
    	//组号不变
    	var message = valid($('#edit' + _columns[0][3].field).val(),$('#edit' + _columns[0][4].field).val());
    	//console.log(values)
    	if(message == null){
    		$.ajax({
                type: "post",
                url: "/entity_eva_ctest_sum/update",
                data: JSON.stringify(values),
                contentType: "application/json",
                success: function (data) {
                    if (data['status'] == "success") {
                        bootoast({
                            message: '修改成功',
                            position: 'top',
                            type: 'success',
                            timeout: 2,
                        });
                        $("#edit_data").modal('hide');
                        $("#data_table").bootstrapTable('refresh');
                    } else {
                        bootoast({
                            message: '修改失败\n' + data['msg'],
                            position: 'top',
                            type: 'danger',
                            timeout: 2,
                        });
                    }
                },
                error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            });
    	}else{
    		bootoast({
                message: message,
                position: 'top',
                type: 'danger',
                timeout: 1.5,
            });
    	}
        
    });

    return oInit;
};

$(function () {
    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();
    
    //显示时间和单位
    $("#nowdate").text(label_eva_wbal_test_unique_time);
    
    //隐藏列
    $('#data_table').bootstrapTable('hideColumn', 'ID');
});


function add_table_foot() {
	$('#wbal_tfoot').remove();
	$('#data_table').append('<tfoot id="wbal_tfoot">\
			<tr id="wbal"><th class="bs-checkbox" style="width: 36px; " data-field="0"><div></div><div/></th>\
				<th style="text-align: center; vertical-align: middle; " data-field=""><div class="th-inner" id=""></div><div class="fht-cell"/></th>\
				<th style="text-align: center; vertical-align: middle; " data-field=""><div class="th-inner" id="">水量合计：</div><div class="fht-cell"/></th>\
				<th style="text-align: center; vertical-align: middle; " data-field=""><div class="th-inner" id=""></div><div class="fht-cell"/></th>\
			<tr> \
				<th class="bs-checkbox" style="width: 36px; " data-field="0"><div></div><div/></th>\
				<th style="text-align: center; vertical-align: middle; " data-field=""><div class="th-inner" id=""></div><div class="fht-cell"/></th>\
				<th style="text-align: center; vertical-align: middle; " data-field=""><div class="th-inner" id="">取水量计算：</div><div class="fht-cell"/></th>\
				<th id="water" style="text-align: center; vertical-align: middle; " data-field=""><div class="th-inner" id="water_value">0</div><div class="fht-cell"/></th>\
			</tr>\
			<tr> \
				<th class="bs-checkbox" style="width: 36px; " data-field="0"><div></div><div/></th>\
				<th style="text-align: center; vertical-align: middle; " data-field=""><div class="th-inner" id=""></div><div class="fht-cell"/></th>\
				<th style="text-align: center; vertical-align: middle; " data-field=""><div class="th-inner" id="">总用水量计算：</div><div class="fht-cell"/></th>\
				<th id="sum" style="text-align: center; vertical-align: middle; " data-field=""><div class="th-inner" id="sum_value" >0</div><div class="fht-cell"/></th>\
			</tr>\
			<tr>\
			<th class="bs-checkbox" style="width: 36px; " data-field="0"><div></div><div/></th>\
                	<td id="note" >注1：“新水量”栏按本企业水源类别及名称（同表B.1 企业取水水源情况表）填报。<br>注2：“非常规水资源”中的“城镇污水再生水”填报在2.1栏。<br>注3：各用水单元水平衡测试表中数据的平均值列入本统计表。 </td >\
            </tr>\
		</tfoot>\
			');
}
function update_table_foot(){	
	var num = get_columns_num(1)+get_columns_num(2)+get_columns_num(3)+get_columns_num(4);
	for(var i=0;i<num;i++){
		$("#wbal").append("<th style='text-align: center; vertical-align: middle; ' data-field=''><div class='th-inner' id='water_"+i+"'></div><div class='fht-cell'/></th>");   
	}
	$('#water').attr('colspan',num+1);
	$('#sum').attr('colspan',num+1);
	$('#note').attr('colspan',num+3);
}

function sumWater(){
	var sum;
	$.ajax({
	    type: "get",
	    url: "/label_eva_ctest_sum/select2",
	    dataType: 'json',
	    async: false,
	    data:{'id':label_water_bala_companyId},
	    contentType: "application/json; charset=utf-8",
	    success: function (data) {
	        if (data['status'] == "success") {
	        	sum = data['rows'];
	        	//console.log("sum:"+sum)
	        } else {
	            bootoast({
	                message: '查询失败\n' + data['msg'],
	                position: 'top',
	                type: 'danger',
	                timeout: 1.5,
	            });
	        }
	    },
	    error: function () {
            bootoast({
                message: '通讯异常',
                position: 'top',
                type: 'danger',
                timeout: 1.5,
            });
        }
	});
	var i =0;
	for(i = 0; i < sum.length-2 ; i++){
		$("#water_"+i).text(sum[i]);
	}
	$('#water_value').text(sum[i+0]);
	$('#sum_value').text(sum[i+1]);
	
}

/**
 * 无依赖合并行
 * @param data  原始数据（在服务端完成排序）data = {'rows':[{id:1,.....},{id:2,.....}]}
 * @param fieldName 合并属性名称数组 field
 * @param colspan 列数 1
 * @param target 目标表格对象 '#data_table'
 */
function mergeCells(data, fieldName, colspan, target) {
	
    if (data.length == 0) {
//         alert("不能传入空数据");
         return;
    }
    var numArr = [];
    var value = data[0][fieldName];
    var num = 0;
    for (var i = 0; i < data.length; i++) {
        if (value != data[i][fieldName]) {
            numArr.push(num);
            value = data[i][fieldName];
            num = 1;
            continue;
        }
        num++;
    }
    numArr.push(num);
    
    var merIndex = 0;
    for (var i = 0; i < numArr.length; i++) {
        $(target).bootstrapTable('mergeCells', { index: merIndex, field: fieldName, colspan: colspan, rowspan: numArr[i] })
        merIndex += numArr[i];
    }
}

//組裝添加動態框
function create_column(csName, enName, value,num) {
    if (typeof(value) == "undefined")
        value = ''
    var pre;
    if(num == 0){
    	pre = "new";
    }else{
    	pre = "edit";
    }
    if(enName == pre+"WATER_CLASS"){
    	var result = '<div class="form-group"><label>'+csName + '</label><select  id="'+ enName +'"value="' + value + '" class="form-control selectpicker" data-live-search="true"></select></div>'
    }else if(enName == pre+"USE_ID" ||enName == pre+"WATER_UNIT_NAME"){
    	var result = '<div class="form-group"><label>' + csName + '</label><input class="form-control" placeholder="必填"  id="' + enName + '" value="' + value + '"></div>';
    }else{
    	var result = '<div class="form-group"><label>' + csName + '</label><input class="form-control" placeholder="选填"  id="' + enName + '" value="' + value + '"></div>';
    }   	
    return result;
}

//返回上级页面
$("#btn_return").click(function () {
    label_water_bala_companyId=label_entity_water_bala_companyID;
    $('#page-wrapper').load('pages/label_entity_water_bala.html');
});

//设置下拉框选择事件，选中后就将对应属性设置到表格exportDataType中
$("#sel_exportoption").change(function () {
  //刷新参数设置
  $('#data_table').bootstrapTable('refreshOptions', {
      exportDataType: $(this).val()
  });
});

function valid(use_id,water_unit_name){
	 if(use_id == ''){
		 return "请输入序号";
	 }
	 if(use_id.match("^[a-zA-Z0-9]+$") == null){
		 return "序号应为数字或字母";
	 }
	 if(water_unit_name == ""){
		 return "请输入用水单元名称";
	 }
	return null; 
}
